<?php

class Search_IndexController extends Zend_Controller_Action
{
   	public function init()
    {
    	// allow everyone access to all actions
        $this->_helper->acl->allow('guest', 'menu');
        $this->_helper->acl->allow('guest', 'advert');
        $this->_helper->acl->allow(null);
    }
    
    
	public function indexAction()
    {
    	$index = new Zend_Search_Lucene(zend_registry::get('config')->search->index->dir);
		//echo "Index contains {$index->count()} documents.<br>";
		
		$search = $this->_getParam('q');//le terme à rechercher
		$hits   = $index->find(strtolower($search));
		$this->view->countIndex = $index->count();
		$this->view->countHits = count($hits);		
		$this->view->search = $search;

		$currentPage = ($this->_getParam('page'))?$this->_getParam('page'):1;
		$paginator = Zend_Paginator::factory($hits);
		$paginator->setCurrentPageNumber($currentPage);
		$paginator->setItemCountPerPage(1);
		$this->view->paginator = $paginator;
    }
    
    
    /**
     * This action is the home page of the website
     *
     */
    public function reindexAction()
    {
        $this->view->title = 'Welcome to Wmp titre!';
        $this->view->headTitle('Welcome');   

        $config = zend_registry::get('config');
       
        setlocale(LC_CTYPE, $config->lc_ctype);
	
		//Open a Lucene index, or create it if it does not exist
		
		$log = new Zend_log(new Zend_log_Writer_Stream($config->lucene->logLile));
		$indexpath = $config->search->index->dir;
		$log->info('Lucene Indexing starting up...');
		$client = new Zend_Http_Client();
		$client->setConfig(array('timeout' => 30));
		
        //First, try opening
        try {
        	$index = Zend_Search_Lucene::open($indexpath);
        	$log->info("Opened existing index in $indexpath");
        } catch (Zend_Search_Lucene_Exception $e){
        	try {
        		$index = Zend_Search_Lucene::create($config->search->index->dir);
        		$log->info("Created new index in $indexpath");
        	} catch(Zend_Search_Lucene_Exception $e) {
        		//If both fail, give up and show error message
        		$log->error("Failed opening or creating index in $indexpath");
        		$log->error($e->getMessage());
        		echo "Unable to open or create index : { $e->getMessage()}";
        		exit(1);
        	}
        }
        
        $targets = array();
        $targets[] = 'http://127.0.0.1/Wmp_cms/www/';
        $targets[] = 'http://127.0.0.1/Wmp_cms/www/index/test/';
        
        //Start iterating
        for($i = 0; $i < count($targets); $i++) {
        	//Fetch content with HTTP Client
        	$client->setUri($targets[$i]);
        	$response = $client->request();
        	
        	if($response->isSuccessful()) {
        		$body =  $response->getBody();
        		$log->info("Fetched ". strlen($body). " bytes from {$targets[$i]}");
        		
        		//Create document
        		$doc = Zend_Search_Lucene_Document_Html::loadHTML($body);
        		//ajout de l'url du document
        		$doc->addField(Zend_Search_Lucene_Field::Text('url',$targets[$i]));
        		
        		//index
        		$index->addDocument($doc);
        		$log->info("Indexed {$targets[$i]}");
        		
        		//Fetch new links
        		$links = $doc->getLinks();
        		foreach ($links as $link) {
        			if( (strpos($link, MATCH_URI) !== false) &&
        			    (! in_array($link, $targets))) 
        			    		$targets[] = $link;
        		}
        	} else {
        		$log->warning("Requesting $url returned HTTP " . $reponse->getStatus());
        	}
        }
        
        $log->info("Iterated over " . count($targets) . " documents");
        $log->info("Optimizing index...");
        $index->optimize();
        
        $index->commit();
        $log->info("Done. Index now contains " . $index->numDocs() . " documents");
        $log->info('Lucene Indexing shutting down');
        exit;
    }

    
}